#include <Windows.h>

#include "tetris.h"
#include "game.h"

static HWND     s_main_wnd;
static void*    s_tetris_game;

#define WIN_W   (WND_W+GetSystemMetrics(SM_CXBORDER)*2+4)
#define WIN_H   (WND_H+GetSystemMetrics(SM_CYBORDER)*2+GetSystemMetrics(SM_CYCAPTION)+4)

static LRESULT CALLBACK WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
  switch (Msg)
  {
  case WM_KEYDOWN:
    key_event(s_tetris_game, (char)wParam);
    break;
  case WM_DESTROY:
    PostQuitMessage(0);
    break;
  default:
    return (DefWindowProc(hWnd, Msg, wParam, lParam));
  }
  return (0);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
  WNDCLASSEX wcex     = { 0 };
  char* class_name    = "tetris";
  MSG msg;

  wcex.cbSize         = sizeof(WNDCLASSEXA); 
  wcex.style          = CS_HREDRAW | CS_VREDRAW;
  wcex.lpfnWndProc    = WindowProc;
  wcex.cbClsExtra     = 0;
  wcex.cbWndExtra     = 0;
  wcex.hInstance      = hInstance;
  wcex.hIcon          = 0;
  wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
  wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  wcex.lpszClassName  = class_name;
  wcex.hIconSm        = 0;
  wcex.lpszMenuName   = 0;
  if (!RegisterClassEx(&wcex)) {
    return (0);
  }

  s_main_wnd = CreateWindow(class_name, "TETRIS", WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU,
    0, 0, WIN_W, WIN_H, 0, 0, hInstance, 0);

  ShowWindow(s_main_wnd, SW_SHOW);
  UpdateWindow(s_main_wnd);

  s_tetris_game = init_game(s_main_wnd);
  for (; s_tetris_game;) {
    if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT) {
        break;
      }
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    } else {
      game_loop(s_tetris_game);
      Sleep(30);
    }
  }

  return (0);
}
